package com.zeyi.chat.handler;

import com.alibaba.fastjson.JSON;
import com.zeyi.chat.annotation.Mapping;
import com.zeyi.chat.dto.Message;
import com.zeyi.chat.po.ChatGroup;
import com.zeyi.chat.po.User;
import com.zeyi.chat.service.GroupService;
import com.zeyi.chat.service.UserService;

/**
 * @author zeyi
 */
public class QueryHandler {

    private QueryHandler() {
    }

    private static class Singleton {
        public static final QueryHandler INSTANCE = new QueryHandler();
    }

    public static QueryHandler getInstance() {
        return QueryHandler.Singleton.INSTANCE;
    }

    /**
     * 处理查找好友
     */
    @Mapping("queryFriend")
    public Message handleFriend(Message message) {
        String email = message.getData();
        User user = UserService.getInstance().findByEmail(email);
        if (user != null) {
            return new Message(true, message.getHandlePath(), JSON.toJSONString(user));
        } else {
            return new Message(false, message.getHandlePath(),null);
        }
    }

    /**
     * 处理查找群
     */
    @Mapping("queryGroup")
    public Message handleGroup(Message message) {
        String groupCode = message.getData();
        ChatGroup group = GroupService.getInstance().findByGroupCode(groupCode);
        if (group != null) {
            return new Message(true, message.getHandlePath(), JSON.toJSONString(group));
        } else {
            return new Message(false, message.getHandlePath(), null);
        }
    }
}
